<?php
namespace app\api\controller;
use think\Db;
use think\facade\{
    View,Env,Config
};
use Thenbsp\Wechat\OAuth\Client;
class Wx
{
    //微信公众号,同一入口
    public function index(){
        //exit($_GET['echostr']);
    }

    //微信页面授权, 用户自动登录
    public function getToken($uid=0){
        $app = model('weixin')->getApp();
        if( !isset($_GET['code']) ) {
            $app->oauth->redirect(url('wx/gettoken','',true,true))->send();
        }else{
            $user = $app->oauth->user();
            $rs = $user->getOriginal();
            $openid = $rs['openid'];
            $result = model('user')->where("wx_openid",$rs['openid'])->find();
            if(!$result){
                $s_id = Db::name('user')->where('id',$uid)->value('id');
                $s_id = $s_id ?:0;
                //注册
                $d = [
                    'wx_openid' => $rs['openid'],
                    's_id' => $s_id,
                    'username' => $rs['nickname'],
                    'sex' => $rs['sex'],
                    'city' => $rs['sex'],
                    'avatar' => $rs['headimgurl'],
                ];
                $rs = model('user')::create($d);
                //介绍人
                if($s_id){
                    $d = [
                        'user_id' => $s_id,
                        'into_user_id' => $rs->id,
                    ];
                    model('userIntroduce')::create($d);
                }
            }
        	$token = model('user')->login($openid, 1);
            $return_url = Env::get('front_token_url')."?token=$token&openid=$openid";
            r($return_url);
        }
    }
}
